<?php


namespace app\common\cachemodel;


use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\BaseCache;
use GuzzleHttp\Exception\GuzzleException;
use think\Cache;
use think\Db;
use think\Log;
use think\response\Json;
use XznsTools\cache\CacheManage;

class AppWeibo extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_weibo';
    protected $cacheModel = 'user.weibo';
    const WB_USERINFO_URL = 'https://api.weibo.com/2/users/show.json';

    /**
     * 添加用户微博信息
     * @param $map
     * @return bool
     */
    public function SaveData($map)
    {
        $res = Cache::get($map['wbuid']);
        if ($res)
        {
            throw new ApiException('当前账号已注册，请勿重复操作');
        }
        Cache::set($map['wbuid'], 1, 2);
        try
        {
            $this->save($map);
        }
        catch (\Exception $e)
        {
            return false;
        }
        return true;
    }


    /**
     * 更新用户微博信息
     * @param $data
     * @param $map
     * @param int $type 1=>wbuid,2=>uid
     * @return bool
     * @throws \Exception
     */
    public function UpdateData($data, $map, $uid, $wbuid)
    {
        try
        {
            $this->where($map)->update($data);
        }
        catch (\Exception $e)
        {
            return false;
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $wbuid . '-1')->rmCache();
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid . '-2')->rmCache();
        return true;
    }

    /**
     * 删除用户微博账号
     * @param $uid
     * @return bool
     * @throws \Exception
     */
    public function DelData($uid)
    {
        $wbInfo = $this->getUserWbInfoFromCache($uid, 2);
        if ($wbInfo)
        {
            try
            {
                $this->where(['uid' => $uid])->delete();
            }
            catch (\Exception $e)
            {
                return false;
            }
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $wbInfo['wbuid'] . '-1')->rmCache();
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid . '-2')->rmCache();
        }
        return true;
    }

    /**
     * 微博登录
     * @param $param
     * @return array|Json
     * @throws ApiException
     * @throws GuzzleException
     * @throws \Exception
     * 微博开放文档 https://open.weibo.com/wiki/%E9%A6%96%E9%A1%B5
     * 微博code https://open.weibo.com/wiki/Help/error
     */
    public function WeiboInfo($param)
    {
        if (!array_key_exists('access_token', $param))
        {
            throw new ApiException('用户token不存在,请重新登录!', 200, 0);
        }
        if (!array_key_exists('uid', $param))
        {
            throw new ApiException('用户ID不存在,请重新登录!', 200, 0);
        }
        //获取用户weibo信息
        $get_user_info = self::WB_USERINFO_URL . '?access_token=' . $param['access_token'] . '&uid=' . $param['uid'];
        $UserResult = Util::curl_get($get_user_info);
        $wb_user = json_decode($UserResult, true);
        if (isset($wb_user['error']))
        {
            throw new ApiException($wb_user['error'], 200, $wb_user['error_code']);
        }
        switch (true)
        {
            case $wb_user['gender'] == 'm'://gender 1=》男，2=》女
                $sex = 1;
                break;
            case $wb_user['gender'] == 'f':
                $sex = 2;
                break;
            default :
                $sex = 0;
        }
        $wb_user['nickname'] = $wb_user['name'];
        $wb_user['headimgurl'] = $wb_user['profile_image_url'] ?? '';
        $wb_user['unionid'] = $param['uid'];
        $wb_user['sex'] = $sex;
        if ($wb_user)
        {
            return $wb_user;
        }
        throw new ApiException('微博授权失败', 200, 0);
    }


    /**
     * 缓存获取用户微博信息
     * @param $param
     * @param int $type 1=>wbuid,2=>uid
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getUserWbInfoFromCache($param, $type = 1)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $param . '-' . $type)->getDataAndSet(function () use ($param, $type)
        {
            return $this->getUserWbInfoFromDb($param, $type);
        }, ['uid', 'uen', 'nickname', 'avatar', 'forbidden', 'email', 'is_first_login', 'uc_id', 'sex', 'has_self_recode', 'wbuid']);

        if ($data && $data['forbidden'] == 1)
        {
            throw new ApiException('该账号禁止登录', 200, 0);
        }
        return $data;
    }

    /**
     * 数据库获取用户微博信息
     * @param $param
     * @param int $type 1=>wbuid,2=>uid
     * @return array
     */
    public function getUserWbInfoFromDb($param, $type = 1)
    {
        switch ($type)
        {
            case 1:
                $where = ['wb.wbuid' => $param];
                break;
            case 2:
                $where = ['wb.uid' => $param];
                break;
            default:
                return [];
                break;
        }
        try
        {
            $data = $this
                ->alias('wb')
                ->field('u.id uid,u.uen,wb.nickname,u.avatar,u.forbidden,u.email,u.is_first_login,u.uc_id,u.sex,u.has_self_recode,wb.wbuid')
                ->join('wechat_backup_07_18_14_43_00.app_user u', 'wb.uid=u.id')
                ->where($where)
                ->findOrFail()->toArray();
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }
}